<template>
  <div id="Content-page">
    <Paging
      :pagData="[
        { name: '每日推荐', router: '/index' },
        { name: '上传推荐', router: '/daily-recom-upload' },
      ]"
    />
    <div class="content-main">
      <div class="global-display global-j-content">
        <div class="left-upload-container">
          <el-upload
            ref="uploadEle"
            :action="imageUrl"
            accept="image/*,.jpg,.jpeg,.png,.webp,.heic,.heif"
            :limit="1"
            :show-file-list="false"
            :on-success="onSuccess"
            :on-error="onError"
            :on-change="onChange"
          >
            <div class="left-upload left-upload-icon">
              <div class="left-upload-icon" v-if="uploadImgurl == ''">
                <el-icon :size="20"><Plus /></el-icon>
                <span>建议上传大小不超过500kb，宽为900px，高为1280px</span>
              </div>
              <div v-else>
                <img :src="previewImageUrl" alt="" />
              </div>
            </div>
          </el-upload>
        </div>
        <div class="right-upload">
          <div class="right-upload-input global-display global-a-items">
            <p>标题</p>
            <el-input placeholder="输入标题" v-model="recomTitle" />
          </div>
          <div class="right-upload-input global-display global-a-items">
            <p>地址</p>
            <el-select
              v-model="recoAddress"
              filterable
              remote
              reserve-keyword
              placeholder="搜索景点地址"
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <div class="right-upload-input global-display global-a-items">
            <p>颜色值</p>
            <div><el-color-picker v-model="color" show-alpha @change="changeColor" /></div>
          </div>
          <div class="right-upload-button">
            <el-button type="success" class="submit-button" :loading="loadIng" @click="subMit"
              >提交</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// 顶部导航组件
import Paging from '@/page/components/Paging-component.vue'
import { Plus } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const $router = useRouter() // 这是路由跳转的
import type { UploadImageResponse } from '@/type/global'
import type { UploadFile, UploadFiles } from 'element-plus'
import { searchCityOptionsAPI, uploadDailyRecomAPI } from '@/api/daily-recom'
const imageUrl = ref('')

const loadIng = ref(false)
// 未上传和已上传的图片展示
const uploadImgurl = ref('')
const uploadEle = ref()
const previewImageUrl = ref('')
// 选择文件时，先进行本地预览，提升移动端体验
function onChange(uploadFile: UploadFile) {
  if (uploadFile && uploadFile.raw) {
    try {
      previewImageUrl.value = URL.createObjectURL(uploadFile.raw as File)
    } catch {
      // 忽略本地预览异常，等待服务端返回
    }
  }
}
// 上传成功
function onSuccess(response: UploadImageResponse) {
  console.log('response',response)
  uploadImgurl.value = response.data[0]
  console.log('uploadImgurl',uploadImgurl.value)
  uploadEle.value.clearFiles()
}
// 上传失败
function onError(error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  console.log(error, uploadFile, uploadFiles)
  ElMessage.error('上传图片失败')
  ElMessage('上传图片失败')
}
// 标题
const recomTitle = ref('')
// 地址
const recoAddress = ref('')
const loading = ref(false)
const options = ref<{ value: string; label: string }[]>([])
// 远程搜索城市
async function remoteMethod(keywords: string) {
  if (keywords == '') return false
  const res = await searchCityOptionsAPI(keywords)
  if (res.data.length > 0) {
    options.value = res.data[0].citys.map((item) => {
      return { value: item.cityName, label: item.cityName }
    })
  } else {
    options.value = []
  }
}
// 颜色
const color = ref('')
function changeColor(event: string | null) {
  color.value = event as string
}
// 提交
async function subMit() {
  try {
    loadIng.value = true
    console.log('uploadImgurl.value',uploadImgurl.value)
    await uploadDailyRecomAPI({
      imageUrl: uploadImgurl.value,
      title: recomTitle.value,
      address: recoAddress.value,
      color: color.value,
    })
    $router.push('/daily-recom')
    loadIng.value = false
  } catch (error) {
    ElMessage.error((error as Error).message || '上传失败')
    loadIng.value = false
  }
}
onMounted(() => {
  imageUrl.value = import.meta.env.VITE_API_IMAGE_URL as unknown as string
})
</script>

<style scoped>
/* 容器卡片化，旅行主题色 */
.content-main {
  max-width: 1100px;
  margin: 32px auto;
  padding: 32px;
  background: var(--bg-1);
  border: 1px solid var(--border);
  border-radius: 16px;
  box-shadow: var(--shadow);
}

/* 双列布局：左上传，右表单 */
.content-main > .global-display {
  display: grid;
  grid-template-columns: 320px 1fr;
  gap: 32px;
  align-items: center;
  justify-content: end;
}
.left-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
/* 上传区域 */
.left-upload {
  width: 100%;
  height: 420px;
  border-radius: 14px;
  border: 2px dashed rgba(52, 179, 227, 0.45);
  color: rgba(52, 179, 227, 0.65);
  background: linear-gradient(180deg, rgba(52, 179, 227, 0.06), rgba(66, 184, 131, 0.04)), #fcfeff;
  overflow: hidden;
  transition: all 0.25s ease;
}
.left-upload:hover {
  border-color: var(--brand-primary);
  box-shadow: 0 8px 24px rgba(52, 179, 227, 0.15);
  transform: translateY(-1px);
}
.left-upload-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  height: 420px;
}
.left-upload-icon span {
  color: var(--muted);
  font-size: 12px;
}
.left-upload img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

/* 右侧表单 */
.right-upload {
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.right-upload-input {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 16px;
  align-items: center;
}
.right-upload p {
  margin: 0;
  color: var(--muted);
  font-weight: 600;
  letter-spacing: 0.2px;
}
.right-upload-input div {
  width: 100%;
}

/* 覆盖输入、选择器、取色器的细节（scoped 下使用 :deep） */
:deep(.el-input__wrapper) {
  height: 44px;
  border-radius: 10px;
  box-shadow: none;
  border: 1px solid var(--border);
  transition: all 0.2s ease;
}
:deep(.el-input__wrapper.is-focus),
:deep(.el-input__wrapper:hover),
:deep(.el-select .el-input__wrapper.is-focus),
:deep(.el-select .el-input__wrapper:hover) {
  border-color: var(--brand-primary);
  box-shadow: 0 0 0 3px rgba(52, 179, 227, 0.1);
}
:deep(.el-select) {
  width: 100%;
}
:deep(.el-color-picker__trigger) {
  height: 44px;
  border-radius: 10px;
  border: 1px solid var(--border);
}

/* 提交按钮区域 */
.right-upload-button {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
}
.submit-button {
  height: 44px;
  padding: 0 22px;
  border-radius: 10px;
  box-shadow: 0 10px 20px rgba(66, 184, 131, 0.18);
  transition:
    transform 0.2s ease,
    filter 0.2s ease;
}
.submit-button:hover {
  transform: translateY(-1px);
}

/* 响应式 */
@media (max-width: 1024px) {
  .content-main {
    margin: 16px;
    padding: 20px;
  }
  .content-main > .global-display {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  .left-upload {
    height: 320px;
  }
  .right-upload-input {
    grid-template-columns: 100px 1fr;
  }
}
@media (max-width: 640px) {
  .right-upload-input {
    grid-template-columns: 1fr;
    gap: 10px;
  }
  .right-upload p {
    text-align: left;
  }
}
</style>
